<?php

namespace App\Repositories\Admin;

use App\BaseRepository;
use App\Model\ProductAttrLabel;
use App\Model\ProductAttrValue;
use Illuminate\Validation\Rule;

class ProductAttrGroupRepository extends BaseRepository
{
    //模型名称
    protected $modelName = "App\Model\ProductAttrGroup";

    protected $allowApiMethod =  ['index','show','store','destroy','destroyBatch'];

    protected function getShowRespondData($model)
    {
        return $model->load('labels','labels.values');
    }

    protected function storeRules()
    {
        return [
            'name' => [
                'required',
                'max:20',
                Rule::unique('product_attr_groups')->whereNull('deleted_at')
            ],
        ];
    }
    protected function updateRules($id)
    {
        return [
            'name' => [
                'required',
                'max:20',
                Rule::unique('product_attr_groups')->whereNull('deleted_at')->ignore($id)
            ],
        ];
    }

    protected function afterStore($model)
    {
        $items = $this->request->input('labels',[]);
        $this->saveLabel($model,$items);
    }

    protected function afterUpdate($model)
    {
        $items = $this->request->input('labels',[]);
        $this->saveLabel($model,$items,false);
    }

    private function saveLabel($model,$items,$is_create=true)
    {
        $labelIds = array();
        $c = count($items);
        for($i=0;$i<$c;$i++){

            $label = false;

            if (!$is_create){
                if (isset($items[$i]['id']) && $items[$i]['id'] != null) {
                    $label = ProductAttrLabel::where('attr_group_id','=',$model->id)->find($items[$i]['id']);
                    if (!$label) continue;
                    $labelIds[] = intval($items[$i]['id']);

                }
            }

            if (!$label) $label = new ProductAttrLabel();

            $label->name = $items[$i]['name'];
            $label->type  = $items[$i]['type'];
            $label->attr_group_id = $model->id;
            $label->sort = isset($items[$i]['sort'])?$items[$i]['sort']:$i;
            $label->save();

            $labelIds[] = $label->id;

            $values = $items[$i]['values'];

            foreach ($values as $k=>$v){
                if (isset($v['value']) && $v['value']!=null){
                    $val = false;
                    if(isset($v['id'])) {
                        $val = ProductAttrValue::find($v['id']);
                    }
                    $av =$val?$val:new ProductAttrValue();
                    $av->value =$v['value'];
                    $av->sort = $k;
                    $av->attr_label_id = $label->id;
                    $av->save();
                }
            }

        }
        $labelIds = array_unique($labelIds);

        if (!$is_create) {
            ProductAttrLabel::where('attr_group_id','=',$model->id)->whereNotIn('id',$labelIds)->delete();
        }
        return true;
    }
}